package com.acme.bankapp.domine.bank;

import com.acme.bankapp.domine.client.Client;
import com.acme.bankapp.exceptions.ClientExistsException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Bank {
    private List<Client> clients;
    private List<ClientRegistrationListener> listeners;

    public Bank() {
        clients = new ArrayList<Client>();
        listeners = new ArrayList<ClientRegistrationListener>();
        addListeners(new DebugListener());
    }

    public Bank(final List<ClientRegistrationListener> listeners) {
        clients = new ArrayList<Client>();
        this.listeners = listeners;
        addListeners(new DebugListener());
    }

    public static class PrintClientListener
        implements ClientRegistrationListener {
        @Override
        public void onClientAdded(final Client client) {
            System.out.println(client.getClientSalutation());
        }
    }

    public static class EmailNotificationListener
        implements ClientRegistrationListener {
        @Override
        public void onClientAdded(final Client client) {
            System.out.println("Notification email for client "
            + client.getClientSalutation() + " to be sent");
        }
    }

    public static class DebugListener implements ClientRegistrationListener {
        @Override
        public void onClientAdded(final Client client) {
            System.out.println(client.getClientSalutation() + " " + new Date());
        }
    }

    public void addListeners(final ClientRegistrationListener
            clientRegistrationListener) {
        listeners.add(clientRegistrationListener);
    }

    public List<Client> getClients() {
        return clients;
    }

    public void addClient(final Client client) throws ClientExistsException {
        if (getClientByName(client.getName()) != null) {
            throw new ClientExistsException("Client with name: "
                + client.getName() + " has already in the bank");
        }
        clients.add(client);
        for (ClientRegistrationListener clientRegistrationListener: listeners) {
            clientRegistrationListener.onClientAdded(client);
        }
    }

    public Client getClientByName(final String name) {
        for (Client client : clients) {
            if (client.getName().compareToIgnoreCase(name) == 0) {
                return client;
            }
        }
        return null;
    }
}
